<template>
  <div>
    <div class="title flex mgt">
      <div class="flex1">教育经历</div>
      <img src="../../assets/home/add.png" alt="" class="add" @click="addEducation">
    </div>
    <div v-for="(item, index) in education" :key="index">
      <div v-if="editingIndex === index" class="flex mainlist-hovers">
        <el-form :model="item" :rules="rules" :ref="(el) => { if (el) formRefs[index] = el }" label-width="100px"
          label-position="top">
          <div class="demo-ruleForm flex-between flex-wrap">
            <el-form-item label="学校名称" prop="school">
              <el-input v-model="item.school"></el-input>
            </el-form-item>
            <el-form-item label="学历" prop="degree">
              <el-select v-model="item.degree" placeholder="请选择">
                <el-option v-for="option in options" :key="option.id" :label="option.name" :value="option.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="专业" prop="major">
              <el-input v-model="item.major"></el-input>
            </el-form-item>
            <el-form-item label="在校时间" prop="range">
              <el-date-picker v-model="item.range" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </div>
          <el-form-item label="专业描述" prop="desc">
            <el-input type="textarea" v-model="item.desc"></el-input>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex1"></div>
            <el-button @click="cancel(index)">取消</el-button>
            <el-button type="primary" @click="save(index)">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="main-jinglist mainlist-hover" @mouseenter="showTooltip(index)" @mouseleave="hideTooltip">
        <div class="flex">
          <div class="flex1">{{ item.school }}</div>
          <div class="time">{{ item.range[0] || '-' }} - {{ item.range[1] || '-' }}</div>
          <div class="flex bianji" v-show="isTooltipVisible && tooltipIndex === index">
            <div class="flex" @click="edit(index)">
              <img src="../../assets/home/bianji.png" alt="" class="del">
              编辑
            </div>
            <div class="flex delnum" @click="remove(index)">
              <img src="../../assets/home/del.png" alt="" class="del">
              删除
            </div>
          </div>
        </div>
        <div class="yuan">{{ item.degree }} {{ item.major }}</div>
        <div class="left-miaoshu">
          <div>专业描述:</div>
          <p>{{ item.desc }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, toRefs, toRaw } from 'vue';
import { ElMessage } from 'element-plus';

const formRefs = ref([]);
const props = defineProps({
  education: {
    type: Array,
    default: () => []  // 添加默认值
  }
});
const { education } = toRefs(props);

const emit = defineEmits(['save']);

const editingIndex = ref(-1);
const isTooltipVisible = ref(false);
const tooltipIndex = ref(-1);

// 学历选项
const options = [
  { id: 1, name: '博士研究生' },
  { id: 2, name: '硕士研究生' },
  { id: 3, name: '大学本科' },
  { id: 4, name: '大学专科' },
  { id: 5, name: '中等专科' },
  { id: 6, name: '职业高中' },
  { id: 7, name: '技工学校（技师班、中级工班、高级工班）' },
  { id: 8, name: '高中' },
  { id: 9, name: '初中' },
  { id: 10, name: '小学' },
  { id: 11, name: '其他' }
];

// 表单校验规则
const rules = {
  school: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
  degree: [{ required: true, message: '请选择学历', trigger: 'change' }],
  major: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
  range: [{ required: true, validator: validateRange, trigger: 'change' }]
};

// 新增教育经历
const addEducation = () => {
  const newEducation = {
    school: '',
    degree: '',
    major: '',
    range: [null, null],
    desc: ''
  };
  education.value.unshift(newEducation);
  editingIndex.value = 0;
};

// 编辑教育经历
const edit = (index) => {
  editingIndex.value = index;
};

// 取消编辑
const cancel = (index) => {
  // 如果是新增的空记录，则删除
  if (editingIndex.value === 0 && !education.value[0].school) {
    education.value.splice(0, 1);
  }
  editingIndex.value = -1;
  const formRef = formRefs.value[index];
  if (formRef) {
    formRef.resetFields()
  }
};

// 保存教育经历
const save = async (index) => {
  const formRef = formRefs.value[index];
  if (!formRef) {
    ElMessage.error('表单引用未找到');
    return;
  }

  await formRef.validate();
  emit('save', {
    type: 'education',
    data: education.value
  });
  editingIndex.value = -1;
};

// 删除教育经历
const remove = (index) => {
  education.value.splice(index, 1);
  emit('save', {
    type: 'education',
    data: education.value
  });
};

// 显示工具提示
const showTooltip = (index) => {
  isTooltipVisible.value = true;
  tooltipIndex.value = index;
};

// 隐藏工具提示
const hideTooltip = () => {
  isTooltipVisible.value = false;
  tooltipIndex.value = -1;
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 日期范围校验
function validateRange(rule, value, callback) {
  if (!value || !value.length || value.some(v => !v)) {
    return callback(new Error('请选择开始时间和结束时间'));
  }

  const [startDate, endDate] = value;
  if (new Date(startDate) > new Date(endDate)) {
    return callback(new Error('结束时间不能早于开始时间'));
  }

  callback();
}
</script>

<style scoped>
@import url("./cmmon.scss");
</style>